package com.lifeonwalden.ms.web.view;

import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.TemplateNameFormat;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;


@Service
public class SystemViewFreemarkerService implements InitializingBean {
    private Configuration cfg;

    @Value("${system.view.basePackagePath:/view/}")
    private String basePackagePath;

    public Template fetch(String path) throws IOException {
        return cfg.getTemplate(path);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        cfg = new Configuration(Configuration.VERSION_2_3_31);
        cfg.setClassLoaderForTemplateLoading(this.getClass().getClassLoader(), basePackagePath);
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        cfg.setLogTemplateExceptions(false);
        cfg.setWrapUncheckedExceptions(true);
        cfg.setFallbackOnNullLoopVariable(false);
        cfg.setTemplateNameFormat(TemplateNameFormat.DEFAULT_2_4_0);
    }
}
